package conf

import (
	"io"
	"os"
)

type AliConf struct {
	Url           string
	Authorization string
	RefreshToken  string
	WorkDir       string
	Agent         string
	DriveId       string
}

var AliConfSet = &AliConf{}

//RefreshTokenFromDisk 获取refreshToken
func RefreshTokenFromDisk() (string, error) {
	file, err := os.Open(AliConfSet.RefreshToken)
	if err != nil {

		bakfile, bsErr := os.Open(AliConfSet.RefreshToken)
		if bsErr != nil {
			return "", bsErr
		}

		defer bakfile.Close()
		if bs, err := io.ReadAll(bakfile); err != nil {
			return "", err
		} else {
			return string(bs), err
		}

	}
	defer file.Close()
	if bytes, err := io.ReadAll(file); err != nil {
		return "", err
	} else {
		return string(bytes), err
	}
}

//StoreRefreshTokenFromDisk 存储refreshToken
func StoreRefreshTokenFromDisk(rf string) error {
	refreshToken, err := RefreshTokenFromDisk()
	if err != nil {
		return err
	}
	bakPath := AliConfSet.RefreshToken + ".bak"
	_ = os.Remove(bakPath)
	file, err := os.Create(bakPath)
	if err != nil {
		return err
	}
	_, err = file.Write([]byte(refreshToken))
	if err != nil {
		return err
	}
	_ = os.Remove(AliConfSet.RefreshToken)
	file, err = os.Create(AliConfSet.RefreshToken)
	if err != nil {
		return err
	}
	_, err = file.Write([]byte(rf))
	if err != nil {
		return err
	}
	return nil
}
